import init_ai from './ai';
import { IActions, IEvents } from './interfaces';

function init_events(data: any, events: IEvents, fire: (type: string, ...args: any[]) => Promise<any>) {
	const data_events = {
		async onLoad(opt: any) {
			// 页面加载 一个页面只会调用一次，query 参数为 my.navigateTo 和 my.redirectTo 中传递的 query 对象。
			data.page = this;
			data.params = data.app.fd.params;
			// Object.freeze(data);	// !!! Could not freeze data here
			await fire('fd-events-init');
			fire('fd-events-ali-page-launch', opt);
		},
		onReady() {
			fire('fd-events-ali-page-ready');
		},
		onShow() {
			// 页面显示 每次页面显示都会调用一次。
			fire('fd-events-ali-page-show');
		},
		onHide() {
			// 页面隐藏
			fire('fd-events-ali-page-hide');
		},
		onUnload() {
			// 页面被关闭
			fire('fd-events-ali-page-unload');
		},
		onTitleClick() {
			// 标题被点击
			fire('fd-events-ali-page-title-click');
		},
		onReachBottom() {
			// 页面被拉到底部
			fire('fd-events-ali-page-reach-bottom');
		},
		onShareAppMessage() {
			// 返回自定义分享信息
			fire('fd-events-ali-page-share-app-message');
		},
		onPullDownRefresh() {
			// 页面被下拉
			fire('fd-events-ali-page-pulldown_refresh');
		}
	};
	Object.keys(events).forEach((event) => {
		data_events[event] = <T extends my.BaseEvent<string, any>>(e: T) => {
			fire(event, e);
		};
	});
	return data_events as any;
}

export default function init_page(events: IEvents, actions: IActions, data: any) {
	const dt = Object.assign(data, { local: {} });
	const ai = init_ai(dt, actions, events);
	return init_events(ai.data, events, ai.emit);
}
